#!/bin/sh
# OPTES CODE launcher (generated by apps/desktop/scripts/linux-launcher.mjs). The Electron binary is optes-code-bin.
here=$(dirname "$(readlink -f "$0")")
bin="$here/optes-code-bin"
helper="$here/chrome-sandbox"
flag=""

asar_sha256="4a07e3d2f8d37fc05c6d2a428ba69c200719d0b11bfda93232ced52d259ccbdc"
if command -v sha256sum >/dev/null 2>&1; then
  actual=$(sha256sum "$here/resources/app.asar" 2>/dev/null | cut -d ' ' -f 1)
  if [ "$actual" != "$asar_sha256" ]; then
    message="OPTES CODE was modified after it was built (resources/app.asar does not match). Reinstall OPTES CODE."
    echo "OPTES: $message" >&2
    command -v notify-send >/dev/null 2>&1 && notify-send "OPTES CODE" "$message" >/dev/null 2>&1
    exit 70
  fi
fi

setuid_root_helper() {
  [ -u "$helper" ] && [ "$(stat -c %u "$helper" 2>/dev/null)" = "0" ]
}

case " $* " in
  *" --no-sandbox "*) ;;
  *)
    if [ "$(id -u 2>/dev/null)" = "0" ]; then
      flag="--no-sandbox"
      echo "OPTES: running as root - Chromium's sandbox is off (--no-sandbox). Run OPTES as a normal user when you can." >&2
    elif setuid_root_helper; then
      :
    elif command -v unshare >/dev/null 2>&1 && unshare --user --map-root-user true >/dev/null 2>&1; then
      [ -f "$helper" ] && flag="--disable-setuid-sandbox"
    elif [ "$(cat /proc/sys/kernel/apparmor_restrict_unprivileged_userns 2>/dev/null)" = "1" ] && [ -e /etc/apparmor.d/optes-code ]; then
      [ -f "$helper" ] && flag="--disable-setuid-sandbox"
    else
      flag="--no-sandbox"
      echo "OPTES: Chromium's sandbox is not available here (no user namespaces, no setuid helper); starting with --no-sandbox." >&2
    fi
    ;;
esac

if [ -z "${HERMES_DESKTOP_PASSWORD_STORE:-}" ]; then
  store=""
  if [ -n "${KDE_SESSION_VERSION:-}" ]; then
    case "$KDE_SESSION_VERSION" in 6) store="kwallet6" ;; 5) store="kwallet5" ;; *) store="kwallet" ;; esac
  elif [ -n "${KDE_FULL_SESSION:-}" ]; then
    store="kwallet"
  elif [ -n "${GNOME_KEYRING_CONTROL:-}" ]; then
    store="gnome-libsecret"
  elif command -v dbus-send >/dev/null 2>&1 && timeout 5 dbus-send --session --print-reply --reply-timeout=2000 \
      --dest=org.freedesktop.secrets /org/freedesktop/secrets org.freedesktop.DBus.Peer.Ping >/dev/null 2>&1; then
    store="gnome-libsecret"
  fi
  if [ -n "$store" ]; then
    HERMES_DESKTOP_PASSWORD_STORE="$store"
    export HERMES_DESKTOP_PASSWORD_STORE
  fi
fi

if [ -n "$flag" ]; then
  exec "$bin" "$flag" "$@"
fi
exec "$bin" "$@"
